<?php
/**
 * alltosun.com 用户模块公用函数库 common.php
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $@Author: 高竞竞 (gaojj@alltosun.com) $
 * $Date: 2011-1-4 下午05:53:30 $
 * $Id: user_helper.php 28986 2014-06-03 08:27:53Z qianym $
 */

require_once MODULE_PATH . '/user/helper/common.php';

class user_helper
{
    public static $publickey = '01CVhZIgSogB85WNhwYVk79A==';

    /**
     * 获取所有有效的用户id
     * @param $time 指定日期的时间戳,不传则返回当前所有,传则返回指定时间之前的
     */
    public static function get_enable_user_ids($time = 0, $filter = array(), $order = '') {
        $filter['status'] = 1;
        $filter['is_enable'] = 1;
        if ($time) {
            $filter['`add_time` <= '] = date('Y-m-d H:i:s', $time);
        }
        return _model('user')->getFields('id', $filter, $order);
    }

    /**
     * 检查用户信息
     * @param unknown_type $info
     * @return multitype:string
     */
    public static function common_check_save($info) {
        if ($info['email']) {
            if (!filter_var($info['email'], FILTER_VALIDATE_EMAIL)) {
                return array('邮箱格式不正确！', 'error', AnUrl('user/admin'));
            }
        }

        if ($info['mobile']) {
            if (trim($info['mobile']) == '') {
                return array('手机号不能为空！', 'error', AnUrl('user/admin'));
            }

            if (!$info['user_name']) {
                $info['user_name'] = $info['mobile'];
            }
        }

        // 去除 roleid
        unset($info['role_id']);

        return array(true, $info);
    }

    /**
     * 更新
     * @param unknown_type $info
     * @param unknown_type $password
     * @param unknown_type $hash
     * @param unknown_type $id
     * @return multitype:string
     */
    public static function common_update_user_info($info, $password, $hash, $id) {
        $info['nickname'] = $info['realname'];

        // 不提交密码，不更新密码
        if ($info['password']) {

            if (!user_helper::is_strlen_scope($password, 6)) {
                return array('密码长度不符合要求！', 'error', AnUrl('user/admin'));
            }

            $info['hash'] = $hash;
            $info['password'] = user_helper::md5_password(trim($password), $hash);
        } else {
            unset($info['password']);
            unset($info['hash']);
        }

        _model('user')->update($id, $info);
        return array(true);
    }

    /**
     * 更新
     * @param unknown_type $info
     * @param unknown_type $password
     * @param unknown_type $hash
     * @param unknown_type $id
     * @return multitype:string
     */
    public static function common_create_user_info($info, $password, $role_id, $hash) {
        // 判断用户信息是否唯一
        $unique_info = user_helper::user_info_unique($info['user_name'], $info['email'], $info['mobile']);
        if ($unique_info['info'] == 'error') {
            return array($unique_info['msg'], 'error', AnUrl('user/admin'));
        }

        if (user_helper::is_pwd_null($password)) {
            return array('密码内不能包含空字符！', 'error', AnUrl('user/admin'));
        }

        if (!user_helper::is_strlen_scope($password, 6)) {
            return array('密码长度不符合要求！', 'error', AnUrl('user/admin'));
        }

        $info['hash'] = $hash;
        $info['password'] = user_helper::md5_password(trim($password), $hash);
        $info['nickname'] = $info['realname'];

        $user_id = _model('user')->create($info);
        if ($user_id) {
            _model('role_user')->create(array('user_id' => $user_id, 'role_id' => $role_id));
        }
        return array(true, $user_id);
    }

    /**
     * 获取总监列表
     */
    public static function get_director_list() {
        $filter = array('role_id' => user_config::DIRECTOR, 'is_enable' => 1);
        $ids = _model('role_user')->getFields('user_id', $filter);
        if ($ids) {
            return _model('user')->getList($ids);
        }

        return false;
    }


    /**
     * 更新用户的状态
     * @param unknown_type $id
     * @param unknown_type $status
     */
    public static function update_mutil_user_status($ids, $status) {
        return _model('user')->update($ids, array('status' => $status));
    }

    /**
     * 更新用户的状态
     * @param unknown_type $id
     * @param unknown_type $status
     */
    public static function update_user_status($id, $status) {
        return _model('user')->update($id, array('status' => $status));
    }

    /**
     * 通过filter获取用户信息
     */
    public static function get_user_info_by_filter($filter) {
        if (!$filter) {
            return array();
        }

        return _uri('user', $filter);
    }

    /**
     * 增加登陆记录
     * @param unknown $user_info 用户信息
     * @return boolean
     */
    public static function create_login_record($user_info) {
        if (!$user_info) {
            return false;
        }

        $role_id = user_helper::get_user_role_id($user_info['id']);
        if (!$role_id) {
            return false;
        }

        $date = date('Y-m-d');
        $week = user_helper::get_date('week');
        $month = user_helper::get_date('month');

        $record_info = _uri('login_record', array('user_id' => $user_info['id']));

        $record = array();
        $record['role_id'] = $role_id;
        $record['user_id'] = $user_info['id'];
        $record['date'] = $date;
        $record['week'] = $week;
        $record['month'] = $month;
        $record['update_time'] = date('Y-m-d H:i:s');

        if (!$record_info) {
            $record['add_time'] = date('Y-m-d H:i:s');
            _model('login_record')->create($record);
        } else {
            _model('login_record')->update($record_info['id'], $record);
        }
    }

    public static function get_user_ids_by_mobile($mobile, $filter = array()) {
        if (!$mobile) {
            return array();
        }

        $filter['mobile'] = $mobile;

        return _model('user')->getFields('id', $filter);
    }

    /**
     * 通过手机号获取用户信息
     * @param unknown $mobile
     * @param unknown $fitler
     * @return multitype:|Ambigous <multitype:, string, unknown, ModelRes, Model>
     */
    public static function get_user_info_by_mobile($mobile, $fitler = array()) {
        if (!$mobile) {
            return array();
        }

        $filter['mobile'] = $mobile;

        return _uri('user', $filter);

    }

    /**
     * 根据手机号获取用户列表
     * @param unknown $mobile
     * @param unknown $filter
     * @return multitype:|Ambigous <multitype:, NULL, mixed, multitype:Ambigous <multitype:, NULL> , array(), unknown>
     */
    public static function get_user_list_by_mobile($mobile, $filter = array()) {
        if (!$mobile) {
            return array();
        }

        $filter['mobile'] = $mobile;

        return _model('user')->getList($filter);
    }

    /**
     * 通过真实姓名获取用户列表
     * @param unknown $realname
     * @return boolean
     */
    public static function get_user_ids_by_realname($realname) {
        if (!$realname) {
            return array();
        }

        return _model('user')->getFields('id', array('realname LIKE' => "%$realname%"));
    }

    /**
     * 根据用户真实姓名获取用户信息列表
     * @param unknown $realname
     * @return multitype:
     */
    public static function get_user_list_by_realname($realname) {
        if (!$realname) {
            return array();
        }

        $user_list = _model('user')->getList(array('realname' => $realname));

        return $user_list;
    }

    /**
     * 通过昵称获取用户ids
     * @param unknown $nickname
     * @param unknown $filter
     * @return multitype:
     */
    public static function get_user_ids_by_nickname($nickname, $filter = array()) {
        if (!$nickname) {
            return array();
        }

        $filter['nickname'] = $nickname;

        return _model('user')->getFields('id', $filter);

    }

    /**
     * 通过昵称获取用户列表
     * @param unknown $nickname
     * @param unknown $filter
     * @return multitype:|Ambigous <multitype:, NULL, mixed, multitype:Ambigous <multitype:, NULL> , array(), unknown>
     */
    public static function get_user_list_by_nickname($nickname, $filter = array()) {
        if (!$nickname) {
            return array();
        }

        $filter['nickname'] = $nickname;

        return _model('user')->getList($filter);

    }

    /**
     * 根据昵称获取用户信息
     * @param unknown $nickname
     */
    public static function get_user_info_by_nickname($nickname, $filter = array()) {
        if (!$nickname) {
            return array();
        }

        $filter['nickname'] = $nickname;

        $user_info = _uri('user', $filter);
        if ($user_info) {
            $role_id = user_helper::get_user_role_id($user_info['id']);
            $user_info['role_type'] = $role_id;
        }

        return $user_info;
    }

    /**
     * 根据用户ID获取用户手机号
     * @param unknown_type $user_id
     */
    public static function is_test_dealers_user($user_id) {
        $user_info = user_helper::get_user_info($user_id);
        if (!$user_info) {
            return false;
        }

        return in_array($user_info['mobile'], user_config::$test_user_mobile);
    }

    /**
     * 格式化用户对外的信息
     * @param unknown_type $user_id
     * @return multitype:unknown Ambigous <>
     */
    public static function format_user_info($user_id) {
        $user_info_profile = array();

        $user_info = self::get_user_info($user_id);
        if ($user_info) {

            $user_info_profile['id'] = $user_info['id'];
            $user_info_profile['avatar'] = $user_info['avatar'];
            $user_info_profile['mobile'] = $user_info['mobile'];
            $user_info_profile['realname'] = $user_info['realname'];
            $user_info_profile['user_name'] = $user_info['user_name'];
            $user_info_profile['gender'] = $user_info['gender'];
        }

        return $user_info_profile;
    }

    /**
     * 更新 access_token
     * @param unknown $user_id
     * @return boolean
     */
    public static function update_access_token($user_id) {
        if (empty($user_id)) {
            return false;
        }

        $user_info = _uri('user', $user_id);
        if (empty($user_info)) {
            return false;
        }

        $update = array();
        $hash = user_helper::random_hash();
        $update['access_token'] = user_helper::set_pwd($user_info["email"], $hash);

        _model('user')->update($user_info['id'], $update);

        return $update['access_token'];
    }


    /**
     * 获取手机号验证码
     */
    public static function getMobileCode($mobile, $send_type, $status = 0) {
        $code_info = _model('mobile_code')->read(array(
            'mobile' => $mobile,
            'res_name' => $send_type,
            'status' => $status
        ), 'ORDER BY `id` DESC');
        if ($code_info) {
            return $code_info;
        } else {
            return false;
        }

    }

    /**
     * 获取地址
     * liw mod 添加随机数 uc浏览器
     */
    public static function get_jump_url($rfUrl = '', $default_url = '') {
        if (empty($rfUrl)) {
            $rfUrl = Request::getParam('rfUrl', '');
        }
        if (!$default_url) {
            $default_url = AnUrl('user/setting');
        }
        $getRf = Request::getRf();
        $rand = '_t=' . time();
        if ($rfUrl) {
            if (strpos($rfUrl, BBS_URL) === 0 || strpos($rfUrl, SITE_URL) === 0) {
                $default_url = $rfUrl;
            }
        }
        if ($getRf) {
            if (strpos($getRf, BBS_URL) === 0 || strpos($getRf, SITE_URL) === 0) {
                $default_url = $getRf;
            }
        }

        $default_url = preg_replace('/(\?|\&)\_t\=\d{10}/', '', $default_url);
        $default_url = false === strpos($default_url, '?') ? $default_url .= '?' . $rand : $default_url .= '&' . $rand;
        return $default_url;
    }

    /**
     * 判断用户名是否符合长度
     * @return boolean
     */
    public static function is_username_len($user_name) {
        if (empty($user_name)) {
            return false;
        }
        $user_name_len = strlen($user_name);
        if ($user_name_len >= 4 && $user_name_len <= 20) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 用户名是否唯一
     */
    public static function is_username_unique($username, $user_id = 0) {
        $username = trim(AnFilter::filter_string($username));
        if (!empty($username)) {
            $user_info = _uri('user', array('user_name' => $username));
            if (!empty($user_info) && $user_info['id'] != $user_id) {
                return false;
            }
        }
        return true;
    }

    /**
     * 邮箱是否唯一
     */
    public static function is_email_unique($email, $user_id = 0) {
        $email = trim(AnFilter::filter_string($email));
        if (!empty($email)) {
            $user_info = _uri('user', array('email' => $email));
            if (!empty($user_info) && $user_info['id'] != $user_id) {
                return false;
            }
        }
        return true;
    }

    /**
     * 手机号码是否唯一
     */
    public static function is_mobile_unique($mobile, $user_id = 0) {
        $mobile = trim(AnFilter::filter_string($mobile));
        if (!empty($mobile)) {
            $user_info = _uri('user', array('mobile' => $mobile));
            if (!empty($user_info) && $user_info['id'] != $user_id) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取用户在用户表hash值
     */
    public static function user_hash($user_id) {
        $hash = _uri('user', $user_id, 'hash');
        return $hash;
    }

    /**
     * 取用户id
     * @param string $access_token
     * @return int $user_id
     * @author weisd
     */
    public static function get_user_id_by_access_token($access_token) {
        $access_token = trim($access_token);
        if (empty($access_token)) {
            return 0;
        }
        $user_info = _uri('user', array('access_token' => $access_token));
        if ($user_info) {
            return $user_info['id'];
        }

        return 0;
    }

    /**
     * 更新用户在线状态
     */
    public static function updata_active() {
        $user_id = user_helper::get_user_id();
        $company_id = company_helper::get_company_id();
        $now = time();

        $filter['company_id'] = $company_id;
        $filter['user_id'] = $user_id;

        $activite = _uri('user_activite', $filter);

        if ($activite) {
            $aa = _model('user_activite')->update($filter, array('activite_time' => $now));
        } else {
            $filter['activite_time'] = $now;
            $bb = _model('user_activite')->create($filter);
        }
    }

    /**
     * 检测邮箱是否是本公司邮箱
     * @param string $email
     * @return bool 是返回真,否则返回假
     */
    public static function is_company_domain($email) {
        $email = trim($email);
        $domain = array_pop(explode('@', $email));
        $company_id = company_helper::get_company_id();
        $company_info = _uri('company', $company_id);
        if ($company_info['domain'] == $domain) {
            return TRUE;
        }
        return FALSE;
    }

    /**
     * 取用户列表首拼音字母
     * @param string $user_name 要转换的汉字
     * @param string 汉字编码字符集 默认UTF8, 可选"gb2312"
     */
    public static function get_first_word($user_name, $type = "all", $code = 'UTF8') {
        require_once MODULE_CORE . '/helper/Pinyin.php';

        return Pinyin::trans($user_name, $type, $code);
    }

    /**
     * 加密,解密字符
     * @param string $string 原文或者密文
     * @param string $operation 操作(ENCODE | DECODE), 默认为 DECODE
     * @param string $key 密钥
     * @param int $expiry 密文有效期, 加密时候有效， 单位 秒，0 为永久有效
     * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
     *
     * @example
     *
     * $a = authcode('abc', 'ENCODE', 'key');
     * $b = authcode($a, 'DECODE', 'key');  // $b(abc)
     *
     * $a = authcode('abc', 'ENCODE', 'key', 3600);
     * $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内，$b(abc)，否则 $b 为空
     */
    public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

        $ckey_length = 4;
        // 随机密钥长度 取值 0-32;
        // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
        // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
        // 当此值为 0 时，则不产生随机密钥


        $key = md5($key ? $key : 'key'); //这里可以填写默认key值
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length)
            : substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE'
            ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry
                ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey [$i] = ord($cryptkey [$i % $key_length]);
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box [$i] + $rndkey [$i]) % 256;
            $tmp = $box [$i];
            $box [$i] = $box [$j];
            $box [$j] = $tmp;
        }

        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box [$a]) % 256;
            $tmp = $box [$a];
            $box [$a] = $box [$j];
            $box [$j] = $tmp;
            $result .= chr(ord($string [$i]) ^ ($box [($box [$a] + $box [$j]) % 256]));
        }

        if ($operation == 'DECODE') {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
                substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)
            ) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc . str_replace('=', '', base64_encode($result));
        }

    }

    /**
     * 判断密码是否有空字符
     */
    public static function is_pwd_null($pwd) {
        if (preg_match('/\s/', $pwd)) {
            return true;
        } else {
            return false;
        }
    }

    //发送激活邮箱
    public static function set_mail_send($email, $uid, $type, $code = '') {
        //生成code
        if (empty($code)) {
            $code = user_helper::random_hash(20);
        }

        $times = time();
        $info = array(
            'code' => $code,
            'email' => $email,
            'user_id' => $uid,
            'times' => $times,
            'res_name' => $type,
            'status' => '0'
        );
        $code_id = _model('email_code')->create($info);
        if ($code_id) {
            $title = mail_config::$send_mail_content[$type]['title'];
            //获取邮箱模板
            $mail_url = ROOT_PATH . '/template/default/mail/' . $type . '.html';
            $mail_str = file_get_contents($mail_url);
            $email_url = urlencode(AnUrl('user/register/check_email') .
                                   '?code=' .
                                   $code .
                                   '&email=' .
                                   $email .
                                   '&type=' .
                                   $type);
            $content = str_replace('(此处是链接)', AnUrl('user/mail_jump?email_url=' . $email_url), $mail_str);
            $return_status = mail_helper::mail($email, $title, $content, 'HTML');
            if ($return_status) {
                return true;
            } else {
                return false;
            }
        }
    }

    /** * 用DES算法加密/解密字符串 * *
     * @param string $string 待加密的字符串
     * @param string $key 密匙，加解密需保持一致
     * @return string 返回经过加密/解密的字符串
     * @copyright       Copyright (c) 2012. dinghaijun.com
     * @modifier        Hey Jun <admin@dinghaijun.com>
     * @lastmodified    Hey Jun   2012-12-10 13:20
     */
    public static function des_encrypt($string, $key) {
        $size = mcrypt_get_block_size('des', 'ecb');
        $string = mb_convert_encoding($string, 'GBK', 'UTF-8');
        $pad = $size - (strlen($string) % $size);
        $string = $string . str_repeat(chr($pad), $pad);
        $td = mcrypt_module_open('des', '', 'ecb', '');
        $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        @mcrypt_generic_init($td, $key, $iv);
        $data = mcrypt_generic($td, $string);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = base64_encode($data);
        return $data;
    }

    /** * 用DES算法加密/解密字符串 * *
     * @param string $string 待加密的字符串
     * @param string $key 密匙，加解密需保持一致
     * @return string 返回经过加密/解密的字符串
     * @copyright       Copyright (c) 2012. dinghaijun.com
     * @modifier        Hey Jun <admin@dinghaijun.com>
     * @lastmodified    Hey Jun   2012-12-10 13:20
     */
    public static function des_decrypt($string, $key) {
        $string = base64_decode($string);
        $td = mcrypt_module_open('des', '', 'ecb', '');
        $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        $ks = mcrypt_enc_get_key_size($td);
        @mcrypt_generic_init($td, $key, $iv);
        $decrypted = mdecrypt_generic($td, $string);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $pad = ord($decrypted{strlen($decrypted) - 1});
        if ($pad > strlen($decrypted)) {
            return '';
        }
        if (strspn($decrypted, chr($pad), strlen($decrypted) - $pad) != $pad) {
            return '';
        }
        $result = substr($decrypted, 0, -1 * $pad);
        $result = mb_convert_encoding($result, 'UTF-8', 'GBK');
        return $result;
    }

    /**
     * 更新session状态
     * @param array $info 用户信息数组
     * @param string 登录方式
     */
    public static function session_update($info, $login_way = 'account') {
        Cookie::set_path(Config::get('cookie_path'));
        Cookie::set_domain(Config::get('cookie_domain'));

        $_SESSION['user_id'] = $info['id'];
        $_SESSION['login_way'] = $login_way;
        // 管理员分离admin_id
        if (user_helper::have_privilege($info['id'])) {
            $_SESSION['admin_id'] = $info['id'];
        }
    }

    /**
     * 检查用户是否有进入后台的权限
     * @param $admin_id 默认为当前登录用户的admin_id
     * @return bool
     */
    public static function have_privilege($admin_id = 0) {
        $admin_id = (int)$admin_id;

        if (empty($admin_id)) {
            $admin_id = user_helper::get_admin_id();
        }

        if (empty($admin_id)) {
            return FALSE;
        }

        $role_ids = user_helper::get_user_role_ids($admin_id);
        if (!$role_ids) {
            return false;
        }
        foreach ($role_ids as $v) {
            $privilege = _uri('role', $v, 'privilege');
            if ($privilege) {
                return TRUE;
            }
        }
        //         foreach ($role_ids as $v) {
        //             $user_role_type = _uri('role', $v, 'type');
        //             if (in_array($user_role_type, array(1))) {
        //                 return TRUE;
        //             }
        //         }

        return FALSE;
        // @FIXME 临时采用privilege来给菜单赋权限 END

        //    return AnAcl::hasDefinedAuth($admin_id);
    }

    /**
     * 设置用户的永久登录状态
     * @param array $info 用户信息数组（必须含id和hash键）
     */
    // public static function remember_me_set($user_info, $password)
    // {
    //     $id_hash = $user_info['id'] . Config::get('cookie_delimiter') . $user_info['hash'] . Config::get('cookie_delimiter') . user_helper::pw_encrypt($password);

    //     $genpass = convert_uuencode($id_hash);

    //     Cookie::set_path(Config::get('cookie_path'));
    //     Cookie::set_domain(Config::get('cookie_domain'));

    //     // 永久登录默认为一年，如需要多种，可以设置为变量
    //     Cookie::set(Config::get('remember_me_name'), $genpass, time() + 3600 * 24 * 14);

    //     // 更新session状态
    //     user_helper::session_update($user_info);
    // }

    /**
     * QQ授权登录提示
     */
    public static function qq_alert_msg($msg) {
        echo <<<END
                    <script type="text/javascript">
                        alert('{$msg}');
                        window.opener.location.reload();
                        setTimeout(function(){
                          window.close();
                        }, 400);
                        /* window.close();
                        parent.window.auth_hide(); */
                    </script>
END;
        exit;
    }

    /**
     * 计算字符串长度
     * @param unknown_type $str
     * @return number
     */
    public static function dstrlen($str) {
        if (strtolower(UC_CHARSET) != 'utf-8') {
            return strlen($str);
        }
        $count = 0;
        for ($i = 0; $i < strlen($str); $i++) {
            $value = ord($str[$i]);
            if ($value > 127) {
                $count++;
                if ($value >= 192 && $value <= 223) {
                    $i++;
                } elseif ($value >= 224 && $value <= 239) {
                    $i = $i + 2;
                } elseif ($value >= 240 && $value <= 247) {
                    $i = $i + 3;
                }
            }
            $count++;
        }
        return $count;
    }

    public static function check_username($username) {
        $username = addslashes(trim(stripslashes($username)));
        $guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
        $len = user_helper::dstrlen($username);
        if ($len > 25 || $len < 3 || preg_match("/\s+|^c:\\con\\con|[%,\*\"\s\<\>\&]|$guestexp/is", $username)) {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    /**
     * 隐藏部分用户邮箱
     */
    public static function hide_email($email) {
        $arr = explode('@', $email);
        $str_len = user_helper::dstrlen($arr[0]);
        if (!$str_len) {
            return false;
        } else {
            if ($str_len <= 2) {
                $arr[0] = substr_replace($arr[0], "***", -1, 1);
            } else {
                if ($str_len <= 6) {
                    $arr[0] = substr_replace($arr[0], "***", -1, 3);
                } else {
                    $arr[0] = substr_replace($arr[0], "****", -2, 4);
                }
            }
        }
        return join('@', $arr);

    }

    /**
     * 隐藏部分用户手机号
     */
    public static function hide_mobile($mobile) {
        return substr_replace($mobile, '****', 3, 4);
    }

    /**
     * 判断必填信息是否唯一
     */
    public static function user_info_unique($username, $email, $mobile = '', $user_id = 0) {
        if (!user_helper::is_username_unique($username, $user_id)) {
            return array('msg' => '当前用户名已被注册，不能重复注册！', 'info' => 'error');
        }

        if (!user_helper::is_mobile_unique($mobile, $user_id)) {
            return array('msg' => '当前手机号已被注册，不能重复注册！', 'info' => 'error');
        }

        if (!user_helper::is_email_unique($email, $user_id)) {
            return array('msg' => '当前邮箱已被注册，不能重复注册！', 'info' => 'error');
        }
        return array('info' => 'ok');
    }

    /**
     * 记住登录的账户名和昵称
     * @param array $info 用户信息数组（必须含id和hash键）
     */
    public static function remember_user_name($user_name, $user_id) {
        $nick_name = user_helper::get_nick_name($user_id);

        $user_hash = $user_name . Config::get('cookie_delimiter') . $nick_name;
        $encode_info = convert_uuencode($user_hash);

        Cookie::set_path(Config::get('cookie_path'));
        Cookie::set_domain(Config::get('cookie_domain'));
        Cookie::set('remember_user', $encode_info, time() + 3600 * 24 * 14);
    }

    /**
     * 根据ID获取用户名
     */
    public static function get_username_by_id($user_id) {
        $username = _uri('user', $user_id, 'user_name');
        return $username;
    }

    /**
     * 根据ID获取用户名
     */
    public static function get_realname_by_id($user_id) {
        $username = _uri('user', $user_id, 'realname');
        return $username;
    }

    /**
     * 根据ID获取是否完善资料
     */
    public static function is_perfect_by_id($user_id) {
        $perfect = _uri('user', $user_id, 'is_perfect');
        return $perfect;
    }

    /**
     * 去除登录用户名
     */
    public static function get_user_name() {
        $remember_user = Cookie::get('remember_user');
        $delimiter = Config::get('cookie_delimiter');
        $remember_user = convert_uudecode($remember_user);
        if (!strpos($remember_user, $delimiter)) {
            return array();
        }
        return explode($delimiter, $remember_user);
    }

    /**
     * 获取用户昵称
     */
    public static function get_nick_name($user_id = '') {
        if ($user_id == '') {
            $user_id = user_helper::get_user_id();
        }

        $user_info = _uri('user', (int)$user_id);

        if (!empty($user_info['real_name'])) {
            $user_name = $user_info['real_name'];
            if ($user_info['gender'] == 0) {
                $user_name .= ' 女士';
            } else {
                $user_name .= ' 先生';
            }
        } elseif (!empty($user_info['user_name'])) {
            $user_name = $user_info['user_name'];
        } elseif (!empty($user_info['nickname'])) {
            $user_name = $user_info['nickname'];
        } else {
            $user_name = '';
        }

        return $user_name;
    }

    /**
     * 获取用户昵称--（完整版）
     */
    public static function get_user_nick_name($user_id = '') {
        if ($user_id == '') {
            return '';
        }

        $user_info = _uri('user', (int)$user_id);
        if (empty($user_info)) {
            return '匿名会员';
        }

        $user_name = $user_info['user_name'];
        if (empty($user_name)) {
            if (!empty($user_info['mobile'])) {
                $user_name = $user_info['mobile'];
            } else {
                $user_name = 'BSZB_' . $user_info['id'] * 2014;
            }
        }
        return $user_name;
    }

    /**
     * 记住用户登录状态
     */
    // public static function remember_me()
    // {
    //     // 已经登录
    //     if (!empty($_SESSION['user_id'])) {
    //         return TRUE;
    //     }
    //     // 没有记住我
    //     if (!$set = Cookie::get(Config::get('remember_me_name'))) {
    //         return FALSE;
    //     }
    //     // cookie格式不对
    //     if (!$set = convert_uudecode($set)) {
    //         user_helper::remember_me_expire();
    //         return FALSE;
    //     }

    //     $cookie_delimiter = Config::get('cookie_delimiter');
    //     // cookie格式不对
    //     if (strpos($set, $cookie_delimiter) === FALSE) {
    //         user_helper::remember_me_expire();
    //         return FALSE;
    //     }

    //     list($user_id, $hash, $password) = explode($cookie_delimiter, $set);

    //     $user_id = (int)$user_id;
    //     $user_info = _uri('user', $user_id);
    //     $password = user_helper::pw_encrypt($password, 'decode');

    //     // 用户不存在
    //     if (empty($user_info)) {
    //         user_helper::remember_me_expire();
    //         return FALSE;
    //     }

    //     // 用户hash与cookie中不等（用户修改密码时需重置hash）
    //     /* if ($user_info['hash'] !== $hash) {
    //         user_helper::remember_me_expire();
    //         return FALSE;
    //     } */
    //     // 更新session状态
    //     user_helper::session_update($user_info);
    //     return TRUE;
    // }


    /**
     * 加密密码
     */
    public static function pw_encrypt($string, $op = 'encode') {
        if (!$string) {
            throw new AnMessageException('pw_encrypt string empty.');
        }

        if ($op == 'decode') {
            $string = convert_uudecode(base64_decode($string));
        }

        $key = 'AAAAB3NzaC1yc2EAAAABIwAAAIEAxb68m9kn8o+tS9UMduJZ1gNOfsu/ecGIS9Bi/Vl7Ytjjd+MacX4zTC/BEtkxIw4fRkmmoy0uutPSHxIXz9sI/+hZq7oOEtw7bns5K7dJYCyIJv3+aOyfz6SaTLPJS+S15Pn3hcuYUnTPsUsDKH/df5s2yc0vrGd0/6A3ZfBDkU8';
        $key_len = strlen($key);
        $str_len = strlen($string);

        $code = '';
        for ($i = 0; $i < $str_len; ++$i) {
            $k = $i % $key_len;
            $code .= $string[$i] ^ $key[$k];
        }

        if ($op == 'decode') {
            return $code;
        }
        return str_replace('=', '', base64_encode(convert_uuencode($code)));
    }

    /**
     * 生成
     */
    public static function gen_pass($string) {
        isset($_SERVER['HTTP_USER_AGENT']) || $_SERVER['HTTP_USER_AGENT'] = __FUNCTION__;
        $key = strtr($_SERVER['HTTP_USER_AGENT'] . __FILE__, ' ', '');
        $key = 'alltosun';
        $key_len = strlen($key);
        $str_len = strlen($string);

        $code = '';
        for ($i = 0; $i < $str_len; ++$i) {
            $k = $i % $key_len;
            $code .= $string[$i] ^ $key[$k];
        }

        return $code;
    }

    /**
     * 使用户的remember_me状态失效
     */
    // public static function remember_me_expire()
    // {
    //     Cookie::set_path(Config::get('cookie_path'));
    //     Cookie::set_domain(Config::get('cookie_domain'));
    //     Cookie::del(Config::get('remember_me_name'));

    //     // 删除session
    //     session_destroy();
    //     return TRUE;
    // }

    /**
     * 使用户的remember_me状态失效
     */
    public static function remember_me_expire() {
        $domain = Config::get('cookie_domain');
        Cookie::set_path(Config::get('cookie_path'));
        Cookie::set_domain($domain);
        Cookie::del('remember_me');

        $domain = str_replace('www.', '', $domain);
        Cookie::set_path(Config::get('cookie_path'));
        Cookie::set_domain($domain);
        Cookie::del('remember_me');

        // 删除session
        session_destroy();
        return TRUE;
    }

    /**
     * 记住用户登录状态
     */
    public static function remember_me() {
        // 已经登录
        if (!empty($_SESSION['user_id'])) {
            return TRUE;
        }

        // 没有记住我,加密不合适
        if (!$set = Cookie::get('remember_me')) {
            return FALSE;
        }

        // cookie格式不对
        if (!$set = user_helper::gen_pass(convert_uudecode(base64_decode($set)))) {
            user_helper::remember_me_expire();
            return FALSE;
        }

        $cookie_delimiter = Config::get('cookie_delimiter');
        // cookie格式不对
        if (strpos($set, $cookie_delimiter) === FALSE) {
            user_helper::remember_me_expire();
            return FALSE;
        }

        list($user_id, $hash) = explode($cookie_delimiter, $set);

        $user_id = (int)$user_id;
        $user_info = _uri('user', $user_id);

        // 用户不存在
        if (empty($user_info)) {
            user_helper::remember_me_expire();
            return FALSE;
        }

        // 用户hash与cookie中不等（用户修改密码时需重置hash）
        /* if ($user_info['hash'] !== $hash) {
            user_helper::remember_me_expire();
            return FALSE;
        } */
        // 更新session状态
        user_helper::session_update($user_info);
        return TRUE;
    }

    private static function encrypt($value) {
        // 空值不加密
        if (!$value) {
            return '';
        }

        $cookie_key = defined("SITE_COOKIE_KEY") ? SITE_COOKIE_KEY : '';
        return $value . substr(md5($value . $cookie_key . self::$publickey), 0, 16);
    }

    /**
     * 设置用户的永久登录状态
     * @param array $info 用户信息数组（必须含id和hash键）
     */
    public static function remember_me_set($user_info) {
        $id_hash = $user_info['id'] . Config::get('cookie_delimiter') . $user_info['hash'];

        $api_genpass = convert_uuencode(user_helper::gen_pass($id_hash));
        $genpass = base64_encode(convert_uuencode(user_helper::gen_pass($id_hash)));

        Cookie::set_path(Config::get('cookie_path'));
        Cookie::set_domain(Config::get('cookie_domain'));
        // 永久登录默认为一年，如需要多种，可以设置为变量
        Cookie::set('remember_me', $genpass, time() + 3600 * 12);

        // 更新session状态
        user_helper::session_update($user_info);
        return self::encrypt($genpass);
    }

    /**
     * 删除公司cookie信息
     */
    public static function remember_company_expire() {
        Cookie::set_path(Config::get('cookie_path'));
        Cookie::set_domain(Config::get('cookie_domain'));
        Cookie::del('remember_company');

        // 删除session
        session_destroy();
        return TRUE;
    }

    /**
     * 随机产生A-Z, a-z, 0-9的字符串
     * @param int $length 随机数的长度
     * @return string
     */
    public static function random_hash($length = 4) {
        $salt = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
        $count = count($salt);
        $hash = '';
        for ($i = 0; $i < $length; $i++) {
            $hash .= $salt[mt_rand(0, $count - 1)];
        }
        return $hash;
    }

    /**
     * 随机产生A-Z, a-z, 0-9的字符串
     * @param int $length 随机数的长度
     * @return string
     */
    public static function random_number_hash($length = 4) {
        $salt = range(0, 9);
        $count = count($salt);
        $hash = '';
        for ($i = 0; $i < $length; $i++) {
            $hash .= $salt[mt_rand(0, $count - 1)];
        }
        return $hash;
    }

    /**
     * 通过用户code取user_id
     * @param string $user_code
     * @return int
     */
    public static function get_user_id_by_code($user_code) {
        if (!$user_code) {
            return 0;
        }

        return _uri('user', array('user_code' => $user_code), 'id');
    }

    /**
     * 取组织下的成员ids
     * @param int $company_id
     * @param int $type
     * @return array
     */
    public static function get_company_user_ids($company_id, $type = 0) {
        $filter = array(
            'company_id' => $company_id
        );
        if ($type) {
            $filter['type'] = $type;
        }

        return _model('company_user')->getFields('user_id', $filter, ' ORDER BY `id` ASC ');
    }

    /**
     * 是否是ace内部员工
     */
    public static function is_ace_staff($user_id = 0) {
        return user_helper::is_certain_role(9, 0, $user_id);
    }

    /**
     * 是否是公司的IT管理员
     */
    public static function is_company_it_manager($company_id, $user_id = 0) {
        return user_helper::is_certain_role(11, $company_id, $user_id);
    }

    /**
     * 是否是公司的人事
     */
    public static function is_company_human_manager($company_id, $user_id = 0) {
        return user_helper::is_certain_role(12, $company_id, $user_id);
    }

    /**
     * 是否是公司的总经理
     */
    public static function is_company_admin_manager($company_id, $user_id = 0) {
        return user_helper::is_certain_role(10, $company_id, $user_id);
    }

    /**
     * 是否是有企业管理权限，　人事或IT管理员
     * @param int $company_id
     * @param int $user_id
     * @return bool
     */
    public static function is_company_manager($company_id = 0, $user_id = 0) {
        if (empty($company_id)) {
            $company_id = company_helper::get_company_id();
        }

        if (empty($user_id)) {
            $user_id = user_helper::get_user_id();
        }

        if (user_helper::is_company_human_manager($company_id, $user_id) ||
            user_helper::is_company_it_manager($company_id, $user_id) ||
            user_helper::is_company_admin_manager($company_id, $user_id)
        ) {
            return TRUE;
        }

        return FALSE;
    }

    /**
     * 是否是某个公司的人员
     */
    public static function is_in_company($company_id, $user_id = 0) {
        if (!$user_id) {
            $user_id = user_helper::get_user_id();
            if (!$user_id) {
                return FALSE;
            }
        }

        return _uri('user', $user_id, 'company_id') == $company_id;
    }

    /**
     * 是否是某一指定的角色
     * @param int $company_id
     * @param int $user_id
     */
    public static function is_certain_role($role_type, $company_id = 0, $user_id = 0) {
        if (!$user_id) {
            $user_id = user_helper::get_user_id();
            if (!$user_id) {
                return FALSE;
            }
        }

        if ($role_type >= 10) {
            if (!$company_id || !user_helper::is_in_company($company_id, $user_id)) {
                return FALSE;
            }
        }

        $role_ids = user_helper::get_user_role_ids($user_id);
        foreach ($role_ids as $k => $v) {
            $tmp_role_type = role_helper::get_role_type($v);
            if ($tmp_role_type == $role_type) {
                return TRUE;
            }
        }

        return FALSE;
    }

    /**
     * 取企业的管理人员
     * @param int $user_id
     * @param int $company_id
     * @return boolean
     */
    public static function is_company_admin($user_id = 0) {
        if (!$user_id) {
            $user_id = user_helper::get_user_id();
        }

        $role_ids = user_helper::get_user_role_ids($user_id);

        return !!array_intersect(array(1, 2, 4), $role_ids);
    }

    /**
     * 检查当前登录的用户是否是超级管理员role==1
     * @param int $admin_id 被访问者的id
     * @return bool
     */
    public static function is_admin($admin_id = 0) {
        if (!$admin_id) {
            static $static_is_admin = NULL;
        } else {
            $static_is_admin = NULL;
        }
        if ($static_is_admin === NULL) {
            if (!$admin_id) {
                $admin_id = user_helper::get_admin_id();
            }
            if (empty($admin_id)) {
                $static_is_admin = FALSE;
            } else {
                $user_role_type = user_helper::get_user_role_type($admin_id);
                $static_is_admin = in_array(5, $user_role_type);
            }
        }

        return $static_is_admin;
    }

    /**
     * 获取当前登录的admin_id
     * @return int
     */
    public static function get_admin_id() {
        static $static_get_admin_id = NULL;
        if ($static_get_admin_id === NULL) {
            $static_get_admin_id = isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 0;
        }
        return $static_get_admin_id;
    }

    /**
     * 获取当前登录的用户id
     * @return int
     */
    public static function get_user_id() {
        //if (ONDEV) return 1;
        static $static_get_user_id = NULL;
        if ($static_get_user_id === NULL) {
            if (isset($_SESSION['user_id'])) {
                $is_regiht = _uri('user', $_SESSION['user_id'], 'status');
                if ($is_regiht) {
                    $static_get_user_id = $_SESSION['user_id'];
                } else {
                    $static_get_user_id = 0;
                }
            } else {
                $static_get_user_id = 0;
            }
        }

        return $static_get_user_id;
    }

    /**
     * 获取登录方式
     */
    public static function get_login_way() {
        if (isset($_SESSION['login_way'])) {
            return $_SESSION['login_way'];
        } else {
            return false;
        }
    }

    public static function get_lenovo_st() {
        $user_id = user_helper::get_user_id();
        $connect_info = _uri('connect_lenovo', array('user_id' => $user_id));
        if ($connect_info && $connect_info['st']) {
            return $connect_info['st'];
        } else {
            return false;
        }
    }

    /**
     * 取得公司的所有员工
     * @param id $company_id
     * @return array
     *
     *public static function get_all_user_ids($company_id)
     *{
     *   return _model('user')->getFields('id', array('company_id'=>$company_id, 'status'=>1));
     *}
     */

    /**
     * 取得所有用户
     * @return array
     */
    public static function get_all_user_ids() {
        return _model('user')->getFields('id', array('status' => 1));
    }

    /**
     * 取得用户的信息，如果不传$user_id，刚取当前登陆用户
     * @param int $user_id
     * @return array
     */
    public static function get_user_info($user_id = 0) {
        static $users;

        if (!$user_id) {
            $user_id = user_helper::get_user_id();
            if (!$user_id) {
                return array();
            }
        }

        if (isset($users[$user_id])) {
            return $users[$user_id];
        }

        $user_info = _uri('user', $user_id);
        if ($user_info) {
            $role_id = user_helper::get_user_role_id($user_info['id']);
            $user_info['role_type'] = $role_id;
        }

        $users[$user_id] = $user_info;

        return $users[$user_id];
    }

    /**
     * 根据用户名获取用户信息和权限字段
     * @param unknown_type $userame
     * @return Ambigous <multitype:, string, unknown, Obj, mixed, number>
     */
    public static function get_user_info_by_relname($userame) {
        $info = _uri('user', array('realname' => $userame));
        if (!empty($info)) {
            $role_id = user_helper::get_user_role_id($info['id']);
            $info['role_type'] = $role_id;
        }

        return $info;
    }

    /**
     * 根据用户名获取用户信息和权限字段
     * @param unknown_type $userame
     * @return Ambigous <multitype:, string, unknown, Obj, mixed, number>
     */
    public static function get_user_info_by_username($userame) {
        $info = _uri('user', array('user_name' => $userame));
        if (!empty($info)) {
            $role_id = user_helper::get_user_role_id($info['id']);
            $info['role_type'] = $role_id;
        }

        return $info;
    }

    /**
     * 获取当前被访问的用户id
     * @return int
     */
    public static function get_visit_id() {
        static $static_get_visit_id = NULL;
        if ($static_get_visit_id === NULL) {
            $url = AnUrl::getInstance();
            if (isset($url['visit_id']) && is_numeric($url['visit_id'])) {
                $static_get_visit_id = $url['visit_id'];
            } else {
                $static_get_visit_id = !empty($url['visit_id']) ? $url['visit_id'] : user_helper::get_user_id();
            }
        }
        if ($static_get_visit_id) {
            $visit_info = _uri('user', $static_get_visit_id);
            if (!$visit_info || $visit_info['status'] != 1) {
                throw new AnMessageException("对不起，您访问的用户不存在！", "error");
            }
        }
        return $static_get_visit_id;
    }

    /**
     * 检查当前登录的用户是否是自己
     * @return bool
     */
    public static function is_self() {
        static $static_is_self = NULL;
        if ($static_is_self === NULL) {
            $static_is_self = user_helper::get_user_id() && user_helper::get_user_id() == user_helper::get_visit_id();
        }
        return $static_is_self;
    }

    /**
     * 获得当前用户的企业id, 或者通过用户id取得company_id
     * @param int $user_id 用户id
     * @return int
     */
    public static function get_user_company_id($user_id = 0) {
        //         if (!$user_id) {
        //             $user_id = user_helper::get_user_id();
        //         }

        //         return _uri('user', $user_id, 'company_id');
    }

    /**
     * 获取用户性别
     */
    public static function get_user_gender($gender_type = 2) {
        $gender_type_arr = user_config::$user_gender_type;
        return $gender_type_arr[$gender_type];

    }

    /**
     * 按照用户空间设置的姓名显示方式显示姓名
     * @param $user_id 要展示的id
     * @param $len 要展示的长度（按两个英文=1个中文）
     * @param $is_hide_mobile 是否隐藏手机号中间四位
     * @param $display_name_type 1: 备注和微信号都展示 2: 展示微信名 3:展示备注名
     */
    public static function display_name($user_id = 0, $len = 0, $is_hide_mobile = false, $display_name_type = 1) {
        if (!$user_id) {
            $user_id = self::get_user_id();
            if (!$user_id) {
                return '';
            }
        }
        static $static_display_name = array();
        if (!isset($static_display_name[$user_id])) {
            $user_id = (int)$user_id;
            if (!$user_id) {
                $static_display_name[$user_id] = '';
            } else {
                $user_info = _uri('user', $user_id);
                if (!$user_info) {
                    $static_display_name[$user_id] = '';
                } else {
                    // 微信表情昵称乱码问题 base64 2014-07-22
                    // if(!empty($user_info['nickname'])) {
                    //     $static_display_name[$user_id] = $user_info['nickname'];
                    // } elseif (!empty($user_info['nickname_base64'])) {
                    //     $static_display_name[$user_id] = base64_decode($user_info['nickname_base64']);
                    // } else {
                    $static_display_name[$user_id] = $user_info['user_name'];
                    //}
                }

            }
        }
        // $display_name_type 2014-01-20 liw add
        $matches = array();
        if ($display_name_type != 1 && preg_match('/(.+)\s\((.+)\)$/', $static_display_name[$user_id], $matches)) {
            if ($display_name_type == 2) {
                $static_display_name[$user_id] = $matches[2];
            } else {
                $static_display_name[$user_id] = $matches[1];
            }
        }

        if ($len > 0) {
            $name = AnString::cutStr($static_display_name[$user_id], $len, '');
            return $name;
        }
        return $static_display_name[$user_id];
    }


    /**
     * 得到真实姓名
     * @param int $user_id
     * @return string
     */
    public static function real_name($user_id) {
        static $static_real_name = array();

        if (!isset($static_real_name[$user_id])) {
            $user_id = (int)$user_id;
            if (!$user_id) {
                $static_real_name[$user_id] = '';
            } else {

                $real_name = _uri('user_profile', array('user_id' => $user_id), 'real_name');
                if ($real_name) {
                    // 真实姓名
                    $static_real_name[$user_id] = $real_name;
                } else {
                    // 账号
                    $static_real_name[$user_id] = user_helper::display_name($user_id);
                }
            }
        }
        return $static_real_name[$user_id];
    }

    /**
     * 返回用户的头像地址（默认为小图）
     * @param $user_id
     * @return string
     */
    public static function avatar($user_id, $size = 'middle') {
        $default_avatar = STATIC_URL . '/images/checkin_default.jpg';

        if (empty($user_id)) {
            return $default_avatar;
        }

        $user_avatar = _uri('user', $user_id, 'avatar');

        if (empty($user_avatar)) {
            return $default_avatar;
        } else {
            if (strpos($user_avatar, 'http://') !== false) {
                return $user_avatar;
            }
        }

        return _image($user_avatar, $size);
    }

    /**
     * 验证密码，同时更新旧系统密码格式为新系统密码格式
     * @param $user_name 登录名
     * @param $password 明文密码
     * @return id
     */
    public static function get_user_id_by_password($user_name, $password) {
        $user_info = _uri('user', array('user_name' => $user_name));
        if (empty($user_info)) {
            return 0;
        }

        $encrypt_passwd = self::md5_password($password, $user_info['hash']); //md5(md5($password) . $user_info['hash']);

        // 新系统的密码，md5
        if (strlen($user_info['password']) == 32 && $encrypt_passwd === $user_info['password']) {
            return $user_info['id'];
        }

        return 0;
    }

    /**
     * 密码加密
     */
    public static function md5_password($password, $hash) {
        $md5_password = md5(md5($password) . $hash);
        return $md5_password;
    }

    /**
     * 第三方密码加密
     */
    public static function auth_md5_password($id) {
        $md5id = md5($id);
        $newstr = substr($md5id, 2, 8);
        return $newstr;
    }

    /**
     * 通过手机验证密码，同时更新旧系统密码格式为新系统密码格式
     * @param $user_name 登录名
     * @param $password 明文密码
     * @return id
     */
    public static function get_user_id_by_mobile($mobile, $password) {
        $user_info = _uri('user', array('mobile' => $mobile));
        if (empty($user_info)) {
            return 0;
        }

        $encrypt_passwd = md5($password . $user_info['hash']);

        // 新系统的密码，md5
        if (strlen($user_info['password']) == 32 && $encrypt_passwd == $user_info['password']) {
            return $user_info['id'];
        }

        return 0;
    }

    /**
     * 根据用户名获取用户id
     * @param $name
     * @return int
     */
    public static function get_user_id_by_name($name) {
        //$company_id = company_helper::get_company_id();
        //$user_info = _uri('user', array('company_id'=> $company_id, 'user_name'=>$name));
        $user_info = _uri('user', array('real_name' => $name));
        if (empty($user_info)) {
            return 0;
        }
        return $user_info['id'];
    }

    /**
     * 根据用户真实姓名获取用户id
     * @param $name
     * @return int
     */
    public static function get_user_id_by_real_name($name) {
        $user_profile_info = _uri('user_profile', array('real_name' => $name));
        if (empty($user_profile_info)) {
            return 0;
        }
        return $user_profile_info['user_id'];
    }

    /**
     * 根据用户名模糊搜索相应的用户id列表
     * @param $name
     * @return array()
     */
    public static function get_user_ids_by_name($name) {
        if (empty($name)) {
            return array();
        }

        return _model('user')->getFields('id', array('user_name like' => "%$name%"));
    }

    /**
     * 根据用户名模糊搜索相应的用户名称列表
     * @param $name
     * @return array()
     */
    public static function get_user_names_by_name($name) {
        $user_names = array();
        if (empty($name)) {
            return $user_names;
        }
        $user_list = _model('user')->getList(array('user_name like' => "%$name%"));
        foreach ($user_list as $k => $v) {
            $user_names[$v['id']] = $v['user_name'];
        }
        return $user_names;
    }

    /**
     * 获取用户所属的角色id列表
     * @param int|array $user_id 用户id或者id数组
     * @param string $order 排序以及LIMIT限制，默认所有角色id
     * @return array
     */
    public static function get_user_role_ids($user_id, $order = 'ORDER BY `id` DESC') {
        if (empty($user_id)) {
            return array();
        }

        $filter = array('user_id' => $user_id);

        $role_ids = _model('role_user')->getFields('role_id', $filter, $order);
        if (!$role_ids) {
            return false;
        }
        return array_unique($role_ids);
    }

    /**
     * 获取后台登陆用户角色id
     */
    public static function get_admin_role_id() {
        $admin_id = user_helper::get_admin_id();
        return user_helper::get_user_role_id($admin_id);
    }

    /**
     * 判断用户是否有此操作权限
     * @param 允许此操作的角色id数组
     */
    public static function is_allow_action($allow_role) {
        if (!is_array($allow_role)) {
            return false;
        }

        $role_id = user_helper::get_admin_role_id();
        if ($role_id) {
            if (!in_array($role_id, $allow_role)) {
                return false;
            }
        } else {
            return false;
        }

        return true;
    }

    /**
     * 获取登陆用户(当用户是助理时)的所有合伙人的用户id
     * @param $user_id 不传默认获取登陆用户的所有合伙人的用户id
     * @return array
     */
    public static function get_assistant_dealer_ids($user_id = 0) {
        $admin_id = 0;
        if ($user_id && is_numeric($user_id)) {
            $admin_id = $user_id;
        } elseif (0 == $user_id) {
            $admin_id = user_helper::get_admin_id();
        } else {
            return array();
        }

        $role_id = user_helper::get_user_role_id($admin_id);

        if (user_config::ASSISTANT != $role_id) {
            return array();
        }

        return _model('user')->getFields('id', array(
            '`dealer_level` >' => 0,
            'assistant_user_id' => $admin_id,
            'status' => 1
        ));

    }

    /**
     * 获取用户的角色id
     * @param unknown $user_id
     * @return multitype:|unknown|number
     */
    public static function get_user_role_id($user_id) {
        if (empty($user_id)) {
            return 0;
        }

        $filter = array('user_id' => $user_id);
        $role_info = _uri('role_user', $filter);
        if ($role_info) {
            return $role_info['role_id'];
        } else {
            return 0;
        }

    }

    /**
     * 获取用户所属的角色类型
     * @param int|array $user_id 用户id或者id数组
     * @param string $order 排序以及LIMIT限制，默认所有角色id
     * @return array
     */
    public static function get_user_role_type($user_id, $order = 'ORDER BY `id` DESC') {
        if (empty($user_id)) {
            return array();
        }

        $filter = array('user_id' => $user_id);

        $role_user_info = _uri('role_user', $filter);
        $role_info = _uri('role', $role_user_info['role_id']);

        return $role_info['type'];
    }

    public static function get_user_role_info($role_id) {
        $role_info = _uri('role', $role_id);
        return $role_info;
    }

    /**
     * 获取某个角色下的用户ids
     * @param int|array $role_id 角色id或者id数组
     * @param string $order 排序以及LIMIT限制，默认100位用户id
     * @return array
     */
    public static function get_role_user_ids($role_id, $order = 'ORDER BY `id` DESC LIMIT 0, 100', $filter = array()) {
        if (empty($role_id)) {
            return array();
        }
        $user_ids = _model('role_user')->getFields('user_id', array('role_id' => $role_id), $order);
        if ($user_ids) {
            $filter['id'] = $user_ids;
            $user_ids = _model('user')->getFields('id', $filter);
        }

        return array_unique($user_ids);
    }

    public static function get_role_user_ids_by_time($role_id, $order = 'ORDER BY `id` DESC LIMIT 0, 100', $filter = array(), $start_time, $end_time) {
        if (empty($role_id)) {
            return array();
        }
        $user_ids = _model('role_user')->getFields('user_id', array(
            'role_id' => $role_id,
            '`add_time` >= ' => $start_time,
            '`add_time` <= ' => $end_time
        ), $order);
        if ($user_ids) {
            $filter['id'] = $user_ids;
            $user_ids = _model('user')->getFields('id', $filter);
        }

        return array_unique($user_ids);
    }

    /**
     * 生成通用用户选择部分被选中的用户用于展示的html
     * @param mixed $id
     * @return string 生成的html
     */
    public static function get_selected_user_html($id) {
        $result = '';
        if (!$id) {
            return $result;
        }
        if (!is_array($id)) {
            $id = explode(',', $id);
        }
        foreach ($id as $k => $v) {
            $user_name = user_helper::display_name($v);
            $result .= '<div class="selectedUserName"><span>' .
                       $user_name .
                       '</span><a href="javascript:void(0);" class="selectedUser' .
                       $v .
                       '">×</a></div>';
        }

        return $result;
    }

    /**
     * 在2个字的姓名之间加上字符填充
     * @param $name
     * @param $pad_string
     * @author gaojj@alltosun.com
     */
    public static function fill_space_between_name($name, $pad_string = '　') {
        if (mb_strlen($name, 'utf-8') == 2) {
            return mb_substr($name, 0, 1, 'utf-8') . $pad_string . mb_substr($name, 1, 1, 'utf-8');
        }
        return $name;
    }

    /**
     * 进后台
     * @param int $user_id
     * @author ninghx@alltosun.com
     */
    public static function be($user_id) {
        if (user_helper::is_admin($_SESSION['admin_id']) || user_helper::is_staff($_SESSION['admin_id'])) {
            $_SESSION['user_id'] = $user_id;
        }
    }

    /**
     * 更改用户信息
     * @param int $user_id
     * @param array $info
     * @return boolean
     */
    public static function update_user_info($user_id, $info) {
        if (!$user_id) {
            return FALSE;
        }

        return _model('user')->update($user_id, $info);
    }

    /**
     * 设置加'盐'密码
     * @param string 用户密码
     * @param $hash 用户hash
     * @return 返回接好的密码
     */
    public static function set_pwd($password, $hash) {
        //return md5($password.$hash);

        $savepassword = base64_encode(sha1($password . $hash, true) . $hash);
        return $savepassword;
    }

    /**
     * 判断用户的登录方式
     * @param 用户名 $username
     * @return number 1 邮箱 2 手机号 3 用户名
     */
    public static function get_user_login_way($username) {
        $int = 0;
        // 邮箱
        //preg_match("/^[0-9a-z_]+@(([0-9a-z]+)[.]){1,2}[a-z]{2,3}$/",$username);
        $int = filter_var($username, FILTER_VALIDATE_EMAIL);
        if ($int) {
            return 1;
        }

        // 手机号
        $int = preg_match("/^1[3|5][0-9]{9}$|^18\d{9}$/", $username);
        if ($int) {
            return 2;
        }

        // 用户名
        return 3;
    }

    /**
     * 验证是否是邮箱
     * @param unknown $email
     * @return number
     */
    public static function is_email($email) {
        $filter = "/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/";
        return preg_match($filter, $email);
    }

    /**
     * 验证用户名是否为数字
     */
    public static function is_number($username) {
        $filter = "/^\d*$/";
        return preg_match($filter, $username);
    }


    /**
     * 字符串是否在规定的长度内
     * @return boolean
     */
    public static function is_strlen_scope($str, $min, $max = 100) {
        //         if(empty(trim($str))) {
        //             return false;
        //         }
        if (mb_strlen($str) >= $min && mb_strlen($str) <= $max) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 验证是否是手机号
     * @param unknown $mobile
     * @return number
     */
    public static function is_mobile($mobile) {
        $filter = "/^1[3,5,8,4,7][0-9]{1}[0-9]{8}$/";
        return preg_match($filter, $mobile);
    }

    /**
     * 获取用户某些字段的信息
     * @param array $fields
     * @param int $user_id
     * @return array
     */
    public static function get_fields_user_info($user_id, $fields = array()) {
        if (!$fields) {
            $fields = array('user_name', 'avatar');
        }
        $fields_str = '';
        foreach ($fields as $v) {
            $fields_str .= "`{$v}`,";
        }
        $fields_str = trim($fields_str, ',');
        $sql = "select {$fields_str} from `user` where id = {$user_id}";

        $user_info = _model('user')->getAll($sql);
        return $user_info[0];
    }

    /**
     * 取某人的上级
     * @param int $user_id
     * @param int $type 1法定直属 10业务领导
     * @return array
     */
    public static function get_user_sup_ids($user_id, $type = 0) {
        $filter = array(
            'user_id' => $user_id
        );
        if ($type) {
            $filter['type'] = $type;
        }
        return _model('user_level_relation')->getFields('leader_id', $filter, ' ORDER BY `leader_id` ASC ');
    }

    /**
     * 取某人的下级
     * @param int $user_id
     * @param int $type 1法定直属 10业务领导
     * @return array
     */
    public static function get_user_sub_ids($user_id, $type = 0) {
        $filter = array(
            'leader_id' => $user_id
        );
        if ($type) {
            $filter['type'] = $type;
        }
        return _model('user_level_relation')->getFields('user_id', $filter, ' ORDER BY `user_id` ASC ');
    }

    /**
     * 通讯录   获取当前通讯录中用户所属分组
     * @param unknown $user_id
     */
    public static function get_address_group_name($user_id) {
        if (!$user_id) {
            return '';
        }

        $group_id = _uri('address_list_relation', array('user_id' => $user_id), 'group_id');

        if (!$group_id) {
            return '';
        }

        return _uri('address_list_group', $group_id, 'title');
    }

    /**
     * 通讯录    获取当前分组下的user_ids
     * @param int $group_id -1 互粉 -2 关注 -3 粉丝  其他为自建分组
     * @param return array
     */
    public static function get_group_user_ids($group_id, $user_id = 0) {
        if (!$group_id) {
            return array();
        }
        if (!$user_id) {
            $user_id = user_helper::get_user_id();
        }

        $user_ids = array();
        $fans_ids = friends_helper::get_user_fans_ids($user_id);// 粉丝
        $follow_ids = friends_helper::get_user_follow_ids($user_id);// 关注
        $friend_ids = array_intersect($fans_ids, $follow_ids);// 好友

        if ($group_id == -1) {
            $user_ids = $friend_ids;
        } else {
            if ($group_id == -2) {
                $user_ids = $follow_ids;
            } else {
                if ($group_id == -3) {
                    $user_ids = $fans_ids;
                } else {
                    if ($group_id == -4) {
                        // 获取未分组的user_ids
                        $outer_user_ids = user_helper::get_company_user_ids(company_helper::get_company_id(), 10);// 全部客户的user_ids
                        $group_user_ids = _model('address_list_relation')->getFields('user_id', array('status' => 1));// 已分租的user_ids
                        $user_ids = array_diff($outer_user_ids, $group_user_ids);// 取差集
                        //an_dump($outer_user_ids, $group_user_ids, $user_ids);exit;
                    } else {
                        // 查询该分组是否存在，并且有权查看
                        $filter = array();
                        $filter['id'] = $group_id;
                        $filter['user_id'] = $user_id;
                        $filter['status'] = 1;
                        $group_info = _model('address_list_group')->read($filter);
                        if (!$group_info) {
                            return array();
                        }

                        $user_ids = _model('address_list_relation')->getFields('user_id', array('group_id' => $group_id));
                    }
                }
            }
        }

        return $user_ids;
    }

    public static function address_list_res_name($type) {
        $config = array(
            '1' => '同事',
            '2' => '客户',
            '3' => '好友',
        );

        if (is_numeric($type)) {
            if (array_key_exists($type, $config)) {
                return $config[$type];
            }
        } else {
            $arr = array_flip($config);
            if (array_key_exists($type, $arr)) {
                return $arr[$type];
            }
        }

        return '';
    }

    /**
     * 获取用户的工作的基本信息
     * @param int $user_id
     * @return array
     */
    public static function get_job_info($user_id = 0) {
        if (!$user_id) {
            $user_id = user_helper::get_user_id();
        }

        return _model('user_job')->read(array('user_id' => $user_id));
    }

    /**
     * 判断用户是否具有当前操作权限
     * @param $admin_id 默认为当前登录用户的admin_id
     * @return bool
     */
    // @FIXME 未使用
    public static function check_privilege($action_name = '') {
        $admin_id = user_helper::get_admin_id();

        if (empty($action_name)) {
            // 获取当前操作的方法名
            $action_name = get_action_name();
            if (!$action_name) {
                return FALSE;
            }
        }
        $action_name = strtolower($action_name);

        // 判断当前操作的方法是否需要权限访问
        $is_privilege = 0;
        $privilege_list = role_config::$privilege_list;
        foreach ($privilege_list as $v) {
            $privilege = array_keys($v['privilege']);
            if (in_array($action_name, $privilege)) {
                $is_privilege = 1;
                break;
            }
        }

        // 判断权限
        if ($is_privilege == 1) {
            $role_ids = user_helper::get_user_role_ids($admin_id);
            foreach ($role_ids as $v) {
                $privilege = _uri('role', $v, 'privilege');
                if ($privilege == '*') {
                    return TRUE;
                }

                if (!empty($action_name)) {
                    $privilege = explode(',', $privilege);
                    if (in_array($action_name, $privilege)) {
                        return TRUE;
                    }
                }
            }
        } else {
            return TRUE;
        }

        return FALSE;
    }

    /**
     * 根据用户的ID，生成用户唯一token
     * @param int $user_id
     */
    public static function create_token($user_id, $hash) {

        $token_key = 'alltosun2013';
        $time = time();

        $token = md5($hash . $user_id . $token_key . $time);

        return $token;
    }

    //临时生成用户
    public static function create_user($user_info, $role_type, $password = '') {

        $hash = user_helper::random_hash();
        if (!$password) {
            $password = user_helper::random_number_hash(6);
        }
        $new_password = user_helper::md5_password($password, $hash);

        $user_info['password'] = $new_password;
        $user_info['hash'] = $hash;

        $user_id = _model('user')->create($user_info);

        if ($user_id) {
            _model('role_user')->create(array('user_id' => $user_id, 'role_id' => $role_type));
            return array('user_id' => $user_id, 'password' => $password);
        }
        return array();
    }

    //重置用户密码和用户组
    public static function reset_password($user_id, $other_info = array(), $role_type = 0, $password = 0) {
        $hash = user_helper::random_hash();
        if (!$password) {
            $password = user_helper::random_number_hash(6);
        }
        $new_password = user_helper::md5_password($password, $hash);
        if ($role_type) {
            _model('role_user')->update(array('user_id' => $user_id), array('role_id' => $role_type));
        }
        $info = array(
            'password' => $new_password,
            'hash' => $hash
        );
        if ($other_info) {
            $info = array_merge($info, $other_info);
        }
        $affected = _model('user')->update($user_id, $info);
        if ($affected) {
            return array('user_id' => $user_id, 'password' => $password);
        }
        return array();
    }

    /**
     * 通过token取用户信息
     * @param string $token
     * @return array
     */
    public static function get_user_info_by_token($token, $use_cache = 1) {
        static $info;

        if ($info && $use_cache) {
            return $info;
        }

        $info = _uri('user', array('token' => $token));
        if (!empty($info)) {
            $role_id = user_helper::get_user_role_id($info['id']);
            $info['role_type'] = $role_id;
        }

        return $info;
    }

    /**
     * 得到市场人员的用户名
     * @param $mobile
     * @param $store_order
     */
    public static function get_store_manger_username($mobile, $store_order) {
        return sprintf("%s%02d", $mobile, $store_order);
    }

    public static function cert_image($image) {
        if (!$image) {
            return '';
        } else {
            return _image($image);
        }
    }

    /**
     * 获取指定区域下的合伙人数量
     * @param $area_code 地区代码 默认是000000时,返回所有的合伙人数量
     * @return int
     */
    public static function get_dealer_num_by_area_code($area_code = '000000') {
        if (!$area_code) {
            return false;
        }

        if ('000000' == $area_code) {
            // 返回全部的合伙人数量
            return _model('role_user')->getTotal(array('role_id' => user_config::AGENCY));
        }

        // 判断传入的参数是省份代码还是城市代码,还是区县代码
        if (0 == $area_code % 10000) {
            // 省份
            return _model('dealer_code')->getTotal(array('province_code' => $area_code), 'GROUP BY `user_id`');
        } elseif (0 == $area_code % 100) {
            // 城市
            return _model('dealer_code')->getTotal(array('city_code' => $area_code), 'GROUP BY `user_id`');
        } else {
            // 区县
            return _model('dealer_code')->getTotal(array('county_code' => $area_code), 'GROUP BY `user_id`');
        }

    }

    /**
     * 获取指定销售助理的所有合伙人的列表
     */
    public static function get_dealer_list_by_assistant_user_id($user_id) {
        if (!$user_id) {
            return array();
        }

        return _model('user')->getList(array('assistant_user_id' => $user_id));
    }

    /**
     * 根据市场人员id获取合伙人id
     * @param int $marketing_id
     * @return int
     * @throws AnException
     */
    public static function get_dealer_id_by_marketing_id($marketing_id = 0) {
        if (!$marketing_id) {
            return 0;
        }

        $marketing_info = _model('user_marketing')->read(array('marketing_id' => $marketing_id));

        if (!empty($marketing_info)) {
            return $marketing_info['agency_id'];
        }

        return 0;
    }

    /**
     * 根据 user_id 获取合伙人 id
     * user_id 可以是任何人
     *
     * 市场人员会提取所属合伙人
     *
     * @param int $user_id
     * @return int
     */
    public static function get_dealer_id_by_user_id($user_id = 0) {
        if (!$user_id) {
            return 0;
        }

        $role_id = self::get_user_role_id($user_id);
        if ($role_id == user_config::MARKETING) {
            $agency_id = self::get_dealer_id_by_marketing_id($user_id);
        } elseif ($role_id == user_config::AGENCY) {
            $agency_id = $user_id;
        } else {
            $agency_id = 0;
        }

        return $agency_id;
    }

    /**
     * 统计指定角色的数量
     * @param $role_id 不传则返回所有用户数量
     */
    public static function get_user_num_by_role_id($role_id = 0, $filter = array()) {
        $user_ids = array();
        if ($role_id) {
            $user_ids = _model('role_user')->getFields('user_id', array('role_id' => $role_id));
        } else {
            $user_ids = _model('role_user')->getFields('user_id', array(1 => 1));
        }

        if ($user_ids) {
            $filter['id'] = $user_ids;
            $filter['status'] = 1;
            $filter['is_enable'] = 1;
            return _model('user')->getTotal($filter);
        } else {
            return 0;
        }

    }

    /**
     * 获取指定角色的用户
     * @param $role_id 权限id
     */
    public static function get_users_by_role_id($role_id = 0, $filter = array()) {
        $user_ids = array();
        $user_ids = _model('role_user')->getFields('user_id', array('role_id' => $role_id));

        if ($user_ids) {
            $filter['id'] = $user_ids;
            $filter['status'] = 1;
            $filter['is_enable'] = 1;
            return _model('user')->getList($filter, ' order BY `id` DESC ');
        } else {
            return null;
        }

    }

    /**
     * 用户数量格式化
     */
    public static function get_format_user_num($user_num = 0) {
        if (!is_numeric($user_num)) {
            return 0;
        }

        $user_num = (int)$user_num;

        if ($user_num > 10000) {
            return round($user_num / 10000, 1) . '万';
        } else {
            return $user_num;
        }
    }

    /**
     * 统计某角色用户的格式化数量
     */
    public static function get_format_user_num_by_role_id($role_id) {
        if (!is_numeric($role_id)) {
            return 0;
        }
        $user_num = SELF::get_user_num_by_role_id($role_id);
        return SELF::get_format_user_num($user_num);
    }


    /**
     * 创建合伙人仓库地址
     * 如果创建的地区已经存在会返回存在的地区的主键id
     * @param $area_code 传递一个六位数的地区编码,精确度最高的地区编码
     * @return int
     * @author gaoa@alltosun.com
     */
    public static function create_dealer_address($area_code, $dealer_address, $user_id, $is_default = 0) {
        if (!$user_id || !$area_code || 6 != strlen($area_code) || !$dealer_address) {
            return 0;
        }
        $user_info = user_helper::get_user_info($user_id);
        if (!$user_info) {
            return 0;
        }

        $dealer_address_info = array();
        $area_info = _widget('area')->get_area_info_by_area_code($area_code);
        if (isset($area_info['county_info'])) {
            $dealer_address_info['county_code'] = $area_info['county_info']['area_code'];
            $dealer_address_info['city_code'] = $area_info['city_info']['area_code'];
            $dealer_address_info['province_code'] = $area_info['province_info']['area_code'];
        } elseif (isset($area_info['city_info'])) {
            $dealer_address_info['city_code'] = $area_info['city_info']['area_code'];
            $dealer_address_info['province_code'] = $area_info['province_info']['area_code'];
        } elseif (isset($area_info['province_info'])) {
            $dealer_address_info['province_code'] = $area_info['province_info']['area_code'];
        } else {
            $dealer_address_info['province_code'] = '000000';
        }

        $dealer_address_info['dealer_address'] = $dealer_address;
        $dealer_address_info['user_id'] = $user_id;

        $res = _uri('dealer_address', $dealer_address_info);
        if ($res) {
            return $res['id'];
        } else {
            $dealer_address_info['add_time'] = date('Y-m-d H:i:s');
            $dealer_address_info['update_time'] = date('Y-m-d H:i:s');
            $dealer_address_info['is_default'] = $is_default;

            return _model('dealer_address')->create($dealer_address_info);
        }
    }


    /**
     * 通过用户的真实姓名或者是昵称获取用户的id
     */
    public static function get_user_id_by_realname($realname) {
        if (!$realname) {
            return 0;
        }

        $nickname = $realname;
        $real_user_ids = _model('user')->getFields('id', array('`realname` LIKE ' => '%' . $realname . '%'));
        $nick_user_ids = _model('user')->getFields('id', array('`nickname` LIKE ' => '%' . $nickname . '%'));
        $user_ids = array_unique(array_merge($real_user_ids, $nick_user_ids));
        if ($user_ids) {
            foreach ($user_ids as $k => $user_id) {
                // 判断查询结果是否是后台用户角色
                $role_id = user_helper::get_user_role_id($user_id);
                if (in_array($role_id, array(
                    user_config::ADMIN,
                    user_config::ASSISTANT,
                    user_config::FINANCIAL_MANAGEMENT,
                    user_config::OPERATOR
                ))) {
                    return $user_id;
                }
            }
        }
    }

    /**
     * 按照时间返回对应的日，周，月，统计用
     * @param unknown_type $type
     * @param unknown_type $time
     * @return string
     */
    public static function get_date($type, $time = '') {
        if (!$time) {
            $time = time();
        }

        if ($type == 'day') {
            $date = date('Y-m-d', $time);
        } else {
            if ($type == 'week') {
                // 第几周
                $date = strftime('%Y%W', $time);
            } else {
                if ($type == 'month') {
                    $date = date('Ym', $time);
                }
            }
        }
        return $date;
    }

    //检查角色是否有权限查看全部(订单,店铺)
    public static function is_all_can_show($role_id) {
        $list = array(
            user_config::ADMIN,
            user_config::FINANCIAL_MANAGEMENT,
            user_config::OPERATOR,
            user_config::DIRECTOR,
            user_config::FACTORY,
        );
        return in_array(intval($role_id), $list);
    }

    //根据区域选择下面的合伙人列表
    public static function get_dealer_ids_by_areas($area_codes = array()) {
        //        $areas 不存在默认全国, 值为身份列表
        // 判断代码是省份,城市还是区县
        $role_id = user_helper::get_admin_role_id();
        if (!user_helper::is_all_can_show($role_id)) {
            $admin_id = user_helper::get_admin_id();
            $province_codes = _model('multiple_area')->getFields('province_code', array(
                'user_id' => $admin_id,
                'status' => 1
            ));

            if ($province_codes) {
                $address_dealer_ids = _model('dealer_address')->getFields('user_id', array('province_code' => $province_codes));
                return $address_dealer_ids;
            }
        }
        return _model('dealer_address')->getFields('user_id');
    }

    /**
     * 获取所有合伙人列表
     *
     * @param array $filter
     * @return mixed
     * @throws AnException
     */
    public static function get_all_dealers_info($filter = array()) {
        $filter = array_merge(array('dealer_level' => array(1, 2)), $filter);
        return _model('user')->getList($filter, ' ORDER BY `realname` ASC');
    }

    /**
     * 获取某级别合伙人列表
     *
     * @param int $level
     * @return array
     * @throws AnException
     */
    public static function get_dealers_level_info($level = 1) {
        if (!in_array($level, array(1, 2))) {
            return array();
        }
        return _model('user')->getList(array('dealer_level' => $level), ' ORDER BY `realname` ASC');
    }

    /**
     * 我是隔壁老王, 让我进去
     *
     * @param $password
     * @return bool
     */
    public static function devergent_wanna_try($password) {
        if (defined('DEVERGENT') && $password === DEVERGENT) {
            if (!isset($_SESSION['devergent_wanna_enter'])) {
                $_SESSION['devergent_wanna_enter'] = 0;
            }
            $_SESSION['devergent_wanna_enter'] += 1;
            if ($_SESSION['devergent_wanna_enter'] > 4) {
                unset($_SESSION['devergent_wanna_enter']);
                return true;
            }
        } else {
            if (isset($_SESSION['devergent_wanna_enter'])) {
                unset($_SESSION['devergent_wanna_enter']);
            }
        }
        return false;
    }

    /**
     * 根据用户ID获取开票权限
     * @author xiaolin
     * @date   2016-09-18
     * @return int
     */
    public static function get_is_invoice($user_id) {
        return _model('user')->field('is_invoice')->read($user_id)['is_invoice'];
    }

    /**
     * 根据用户ID获取抱抱币
     * @author xiaolin
     * @date   2016-09-19
     * @return decimal
     */
    public static function get_bbcoin_by_id($user_id) {
        return _uri('user', $user_id, 'bbcoin');
    }

    /**
     * 根据用户ID获取余额
     * @author xiaolin
     * @date   2016-09-19
     * @return decimal
     */
    public static function get_user_money_by_id($user_id) {
        return _uri('user', $user_id, 'user_money');
    }

    /**
     * 根据用户ID获取积分
     * @author xiaolin
     * @date   2016-09-19
     * @return decimal
     */
    public static function get_score_by_id($user_id) {
        return _uri('user', $user_id, 'score');
    }
}


